package com.youlian.manager.param;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import android.os.Debug;
import android.util.Log;

import com.youlian.common.Constants;
import com.youlian.utils.Md5Util;
import com.youlian.utils.MyLog;



/**
 *
 * @author simon
 *
 */
public class ParametersUtils {
	/** 请求url **/
	private String reqURL;
	/** 参数TreeMap **/
	private TreeMap<String, String> params = new TreeMap<String, String>(
			new Comparator<Object>() {
				public int compare(Object o1, Object o2) {
					if (o1 == null || o2 == null)
						return 0;
					else
						return String.valueOf(o1).compareTo(String.valueOf(o2));
				}
			});

	/**
	 * 添加系统级别的参数
	 *
	 * @param baseParam
	 *            构造对象
	 */
	public ParametersUtils(BaseParam baseParam) {
		addStringParam("user_token", baseParam.getUser_token());
		addStringParam("service", baseParam.getService());
//		addStringParam("ver", baseParam.getVer());
//		addStringParam("fields", baseParam.getFields());
//		addStringParam("format", baseParam.getFormat());
	}

	/**
	 * 添加参数方法
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public void addParam(String key, String value) {
		if (null == key || "".equals(key) || null == value) {
		} else {
			params.put(key.trim(), value.trim());
		}
	}

	/**
	 * 添加string类型的参数
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public void addStringParam(String key, String value) {
		addParam(key, value);
	}

	/**
	 * 添加Int类型的参数
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public void addStringParam(String key, Number value) {
		addParam(key, value.toString());
	}

	/**
	 * 签名方法
	 *
	 * @param params
	 * @param charset
	 * @return
	 */
	public void makeSign(TreeMap<String, String> params, String secretKey,
			String charset) {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

		try {
			for (String key : params.keySet()) {
				byteStream.write(params.get(key).getBytes(charset));
			}
			byteStream.write(secretKey.getBytes(charset));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		byte[] array = byteStream.toByteArray();
		System.out.println("sing zuhe:" + array);

		String sign = Md5Util.makeMd5Sum(array);

		if (Debug.isDebuggerConnected()) {
			Log.i("sign :", sign);
		}
		addStringParam("api_sign", sign);

	}
	/**
	 * 获取请求url
	 * @return
	 */
	public String getReqURL() {
		BaseParam baseParam = new BaseParam();
		addStringParam("api_key", baseParam.getApi_key(Constants.API_KEY));
		makeSign(params, baseParam.getApi_secret(Constants.API_SECRET),baseParam.get_input_charset());
		StringBuilder urlBuilder = new StringBuilder();

		Iterator iter = params.entrySet().iterator();
		urlBuilder.append(Constants.YOULING_REQUEST_URL);

		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			urlBuilder.append("&" + key + "=" + val);
		}

		if (!urlBuilder.toString().equals("")) {
			reqURL = urlBuilder.toString().replaceFirst("&", "?");

		}
		if (reqURL.indexOf("service") < 0) {
			throw new IllegalArgumentException("参数异常 ,请设置service参数");
		}
		if (reqURL.indexOf("api_key") < 0) {
			throw new IllegalArgumentException("参数异常 ,请设置api_key参数");
		}

		MyLog.debug(getClass(), reqURL);

		return reqURL;
	}
}
